package models

import (
	"time"

	"github.com/astaxie/beego/validation"
)

// Tag 标签
type Tag struct {
	//gorm.Model
	Id        int       `gorm:"primaryKey" json:"id" form:"id"`
	Status    int       `json:"status" form:"status"`
	Name      string    `valid:"Required;" json:"name" form:"name"` // 不能为空
	Slug      string    `json:"slug" form:"slug"`
	CreatedAt time.Time `json:"createdAt" form:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt" form:"updatedAt"`
}

// TableName 表名
func (t *Tag) TableName() string {
	return TableName("tags")
}

// 自定义验证规则
func (m *Tag) SelfValid() (msg interface{}) {
	var model Tag
	info := map[string]interface{}{}
	valid := validation.Validation{}
	if b, _ := valid.Valid(m); !b {
		for _, err := range valid.Errors {
			return err.Message
		}
	}
	if m.Id != 0 {
		Db.Model(&model).Where("name = ?", m.Name).Where("id <> ?", m.Id).Find(&info)
	} else {
		Db.Model(&model).Where("name = ?", m.Name).Find(&info)
	}
	// Name 唯一
	if len(info) > 0 {
		return "名称唯一，不能重复"
	}
	return nil
}
